﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Threading;
using CrawlerCore;
using PhotobucketNet;
using WCrawlerLib;

namespace WCrawler.Controls
{
    public partial class ucImage : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        
        public Post GetCurrentPost()
        {
            Post objPost = null;
            if (Session["PostId"] != null)
            {
                objPost = new Post();
                objPost = objPost.GetPost((int)Session["PostId"]);
            }

            if (objPost != null)
            {
                txtImageTitle.Text = objPost.PostTitle;
                Topic objRootTopic = objPost.Topic.GetRootTopic(objPost.TopicId);
                txtAlbum.Text = objRootTopic.TopicName;
                txtLocalPath.Text = WebConfiguration.LocalPath;
                txtPrimaryImage.Text = "";
                txtScreenShot.Text = "";
                
            }
            return objPost;
        }

        public event EventHandler ImageLinqDataSourceSelecting;
        protected void ImageLinqDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            if (ImageLinqDataSourceSelecting != null)
                ImageLinqDataSourceSelecting(sender,e);

            if (Session["PostId"] != null)
            {
                ImagePost objImagePost = new ImagePost();
                int postId = (int)Session["PostId"];
                e.Result = objImagePost.GetImagesByPost(postId);
            }
        }

        public void GridViewPostImages_DataBind()
        {
            gridViewPostImages.DataBind();
        }

        private string FormatTitleName(string name)
        {
            return name.Replace(" ", "").Replace("/", "");
        }

        protected void btnUploadImagePopup_Click(object sender, EventArgs e)
        {
            string imgTitle = FormatTitleName(txtImageTitle.Text);
            string imgName = "";
            Dictionary<string, string> imgList = new Dictionary<string, string>();
            BrowserSession_General br = new BrowserSession_General();

            //Add primary image
            if (txtPrimaryImage.Text != string.Empty)
            {
                imgList = new Dictionary<string, string>();
                imgName = imgTitle + "_primary";
                imgList.Add(imgName, txtPrimaryImage.Text);

                //Save in database
                ImagePost imgPost = new ImagePost();
                if (checkBoxIsOrginalImages.Checked)
                    imgPost.AddOriginalUrl((int)Session["PostId"], imgList, true);
                else
                    imgPost.AddImageUrl((int)Session["PostId"], imgList, true);
            }

            //Add screenshot
            if (txtScreenShot.Text != string.Empty)
            {
                imgList = new Dictionary<string, string>();
                string imageList = txtScreenShot.Text.Replace("[IMG]", "").Replace("[/IMG]", "\n").Trim();
                string[] screenshots = imageList.Split(new char[] { '\n' });
                List<string> screenList = new List<string>();
                int count = 1;
                foreach (string screenshot in screenshots)
                {
                    if (screenshot.Trim() != "")
                    {
                        imgName = imgTitle + "_screenshot" + count++.ToString();
                        imgList.Add(imgName, screenshot);
                    }
                }

                //Save in database
                ImagePost imgPost = new ImagePost();
                if (checkBoxIsOrginalImages.Checked)
                    imgPost.AddOriginalUrl((int)Session["PostId"], imgList, false);
                else
                    imgPost.AddImageUrl((int)Session["PostId"], imgList, false);
            }
            
            gridViewPostImages.DataBind();
        }

        protected void btnGetIMGTags_Click(object sender, EventArgs e)
        {
            if (Session["PostId"] != null)
            {
                ImagePost objImgPost = new ImagePost();
                Dictionary<int,string> imgDict = objImgPost.GetImagesByPostWithTag((int)Session["PostId"]);

                txtIMGTags.Text = imgDict[0] + "\n\n" + imgDict[1];
                mdlIMGTagPopup.Show();
            }
        }

        protected void btnUploadImages0_Click(object sender, EventArgs e)
        {
            //Get infor
            Post objPost = GetCurrentPost();
            if (objPost != null)
            {
                btnUploadImagePopup.Text = "Add Images";
                mpeNewImage.Show();
            }
        }

        protected void btnLoginPhotobucket_Click(object sender, EventArgs e)
        {
            PhotobucketNet.Photobucket pbn = new Photobucket(WebConfiguration.Photobucket_ApiKey, WebConfiguration.Photobucket_ApiSecret);
            pbn.LaunchUserLogin();
            Thread.Sleep(WebConfiguration.Photobucket_WaitTime);
            Session["PhotobucketNet"] = pbn;
        }

        protected void btnUploadToPhotobucket_Click(object sender, EventArgs e)
        {
            PhotobucketNet.Photobucket pbn = (PhotobucketNet.Photobucket)Session["PhotobucketNet"];
            if (pbn == null)
                return;

            if (pbn.AppAuthorized)
            {
                try
                {
                    pbn.RequestUserToken();
                    Session["PhotobucketNet"] = pbn;
                    GetCurrentPost();
                    Album imgAlbum = new Album(pbn.Username + "/" + txtAlbum.Text);
                    BrowserSession_General br = new BrowserSession_General();
                    string imgLocalUrl;
                    Dictionary<string, string> result = new Dictionary<string, string>();
                    foreach (GridViewRow r in gridViewPostImages.Rows)
                    {
                        int imgPostId = (int)gridViewPostImages.DataKeys[r.RowIndex].Value;
                        ImagePost objImagePost = new ImagePost();
                        objImagePost = objImagePost.GetImagePost(imgPostId);
                        //download image
                        imgLocalUrl = br.DownloadImage(objImagePost.OriginalUrl, Server.MapPath(txtLocalPath.Text), FormatTitleName(objImagePost.ImageTitle));
                        //upload image to photobucket
                        MediaItem mi = new MediaItem(pbn.Username, objImagePost.ImageTitle, System.IO.File.Open(imgLocalUrl, System.IO.FileMode.Open, System.IO.FileAccess.Read), MediaType.Image);
                        mi.Title = objImagePost.ImageTitle;
                        mi = pbn.UploadMediaItemToAlbum(mi, imgAlbum);
                        //save uploaded image url to database
                        objImagePost.UpdateImageUrl(mi.Url);
                    }

                    gridViewPostImages.DataBind();
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                    //lblMessageImage.Text = ex.Message;
                }
            }
        }

        protected void gridViewPostImages_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void gridViewPostImages_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.FindControl("OriginalUrl") != null)
                {
                    System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)e.Row.FindControl("OriginalUrl");
                    if (img.ImageUrl == "")
                        img.Visible = false;
                }

                if (e.Row.FindControl("ImageUrl") != null)
                {
                    System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)e.Row.FindControl("ImageUrl");
                    if (img.ImageUrl == "")
                        img.Visible = false;
                }
            }
        }

    }
}